package com.cdqidi.interceptor;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.cdqidi.service.WxAuthService;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

public class WxVerInterceptor implements Interceptor{
	private static Logger logger = Logger.getLogger(WxVerInterceptor.class);
	@Override
	public void intercept(Invocation inv) {
		Controller c = inv.getController();
		String userAgent = c.getRequest().getHeader("User-Agent");
		String pattern = "(?i)MicroMessenger/([\\d\\.]+)";
		// 创建 Pattern 对象
		Pattern r = Pattern.compile(pattern);
		// 现在创建 matcher 对象
		Matcher m = r.matcher(userAgent);
		if (m.find()) {
			try {
				String version = m.group(1);
				if(!"".equals(version)&&null!=version) {
					String ver = version.substring(0,1);
					int _ver = Integer.parseInt(ver);
					if(_ver<5) {
						logger.error("微信版本号小于5.0,userAgent: "+userAgent);
						WxAuthService.getInstance().render500(c, "请使用微信5.0以上版本");
						return;
					}
				}else {
					logger.error("取不到微信版本号,userAgent: "+userAgent);
					WxAuthService.getInstance().render500(c, "请在微信中使用该功能");
					return;
				}
			}catch (IndexOutOfBoundsException | NumberFormatException e) {
				logger.error("异常,userAgent: "+userAgent);
				WxAuthService.getInstance().render500(c, "请在微信中使用该功能");
				return;
			}
		} else {
			logger.error("正则匹配错误,userAgent: "+userAgent);
			WxAuthService.getInstance().render500(c, "请在微信中使用该功能");
			return;
		}
		inv.invoke();
	}
}